﻿using FreeSql;
using FreeSql.DataAnnotations;
using FreeSql.Internal.ObjectPool;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using Newtonsoft.Json;
using PropertyChanged;
using sys_Print.DataAsset;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Resources;

namespace sys_Print.ViewModel
{
    [AddINotifyPropertyChangedInterface]
    public class ContentMappingViewModel : ViewModelBase
    {
        [DoNotNotify]
        private readonly IFreeSql _fsql;

        public int SelectedItemIndex { get; set; }
        public ObservableCollection<ContentTemplateMapping> DataList { get; set; } = new ObservableCollection<ContentTemplateMapping>();
        public List<PrintCanvasModel> CanvasIds { get; set; }
        public List<Organization> Organizations { get; set; }
        public ObservableCollection<ContentType> ContentTypes { get; set; }
        public List<PrintModelType> PrintModelTypes { get; set; }
        public ObservableCollection<string> ProductSeries { get; set; }
        public PrintModelType SelectedPrintModelType { get; set; }
        public Organization SelectedOrganization { get; set; }
        public string SelectedProductSerie { get; set; }
        public RelayCommand SubmitButtonCommand { get; private set; }
        public RelayCommand AddButtonCommand { get; private set; }
        public RelayCommand RefreshButtonCommand { get; private set; }
        public RelayCommand SelectedCommand { get; private set; }
        public RelayCommand<DataGridRow> CheckCommand { get; private set; }
        public RelayCommand<DataGridRow> CustomCheckCommand { get; private set; }
        public RelayCommand<DataGridRow> DeleteButtonCommand { get; private set; }

        public ContentMappingViewModel() 
        {
            // 获取配置好的FreeSql实例
            _fsql = App.FsqlDB;

            SubmitButtonCommand = new RelayCommand(new Action(OnSubmitButton));
            AddButtonCommand = new RelayCommand(new Action(OnAddButton));
            RefreshButtonCommand = new RelayCommand(new Action(OnRefreshButton));
            SelectedCommand = new RelayCommand(new Action(OnSelected));
            CheckCommand = new RelayCommand<DataGridRow>(new Action<DataGridRow>(OnCheckComboBox));
            CustomCheckCommand = new RelayCommand<DataGridRow>(new Action<DataGridRow>(OnCustomCheckComboBox));
            DeleteButtonCommand = new RelayCommand<DataGridRow>(new Action<DataGridRow>(OnDeleteButton));

            List<ContentType> lists = _fsql.Select<ContentType>().ToList();
            ContentTypes = new ObservableCollection<ContentType>(lists);

            Organizations = _fsql.Ado.Query<Organization>("SELECT * FROM ais20160331162100.dbo.t_Item WHERE FDeleted = 0 AND FItemClassID = 1 AND FLevel =1 Order By FNumber").ToList();
            List<string> list = _fsql.Ado.Query<string>("SELECT be.FNumber FROM ais20160331162100.dbo.t_BOS200000005Entry2 be LEFT JOIN ais20160331162100.dbo.t_BOS200000005 b ON b.FID = be.FID WHERE b.FDiscontinued = 0 ORDER BY be.FNumber").ToList();
            ProductSeries = new ObservableCollection<string>(list);
            ProductSeries.Insert(0,"00");
            PrintModelTypes = _fsql.Select<PrintModelType>().Where(a => a.State == true).ToList();

            CanvasIds = _fsql.Select<PrintCanvasModel>().Where(a => a.ControlType == "DataGrid").ToList();

            OnRefreshButton();
        }

        private void OnCustomCheckComboBox(DataGridRow dataGridRow)
        {
            if (dataGridRow != null && dataGridRow.DataContext is ContentTemplateMapping item)
            {
                CheckComboBox checkComboBox = DemoViewModel.FindVisualChild<CheckComboBox>(dataGridRow, "CustomCheckComboBox");

                if (checkComboBox != null && checkComboBox.Tag.ToString() == "Custom")
                {
                    List<string> strs = new List<string>();
                    foreach (Organization organization in checkComboBox.SelectedItems)
                    {
                        strs.Add(organization.FNumber);
                    }

                    string result = string.Join(",", strs);
                    item.CustomId = result;
                }

            }
        }

        private void OnCheckComboBox(DataGridRow dataGridRow)
        {
            if (dataGridRow != null && dataGridRow.DataContext is ContentTemplateMapping item) {
                CheckComboBox checkComboBox = DemoViewModel.FindVisualChild<CheckComboBox>(dataGridRow, "CheckComboBox");

                if (checkComboBox != null && checkComboBox.Tag.ToString() == "ProductSerie")
                {
                    IList strs = checkComboBox.SelectedItems;
                    string result = string.Join(",", strs.OfType<string>().ToList());
                    item.ProductSeriesId = result;
                }
            } 
        }

        /// <summary>
        /// 删除行
        /// </summary>
        /// <param name="row"></param>
        private void OnDeleteButton(DataGridRow row)
        {
            if (row != null && row.DataContext is ContentTemplateMapping dataItem)
            {
                SelectedItemIndex = -1;
                DataList.Remove(dataItem);

                _fsql.Delete<ContentTemplateMapping>().Where(dataItem).ExecuteAffrows();
            }
        }

        /// <summary>
        /// 过滤查询
        /// </summary>
        private void OnSelected()
        {
            List<ContentTemplateMapping> list = _fsql.Select<ContentTemplateMapping>().OrderBy(a => a.Id).ToList();
            
            if (SelectedPrintModelType != null) { list = list.Where(a => a.PrintModelId == SelectedPrintModelType.Id).ToList(); }
            if (SelectedOrganization != null) { list = list.Where(a => a.CustomId == SelectedOrganization.FNumber).ToList(); }
            if (SelectedProductSerie != null) { list = list.Where(a => a.ProductSeriesId == SelectedProductSerie).ToList(); }

            DataList = new ObservableCollection<ContentTemplateMapping>(list);
        }

        /// <summary>
        /// 新增行
        /// </summary>
        private void OnAddButton()
        {
            DataList.Add(new ContentTemplateMapping());
        }

        /// <summary>
        /// 提交数据
        /// </summary>
        private void OnSubmitButton()
        {
            // 获取在 DataGrid 中所做的更改
            var modifiedItems = DataList.Where(item => item.IsChanged);

            using (Object<DbConnection> conn = _fsql.Ado.MasterPool.Get())
            {
                using (DbTransaction transaction = conn.Value.BeginTransaction())
                {
                    try
                    {
                        foreach (ContentTemplateMapping item in modifiedItems)
                        {
                            //验证数据是否重复


                            _fsql.InsertOrUpdate<ContentTemplateMapping>().SetSource(item).WithTransaction(transaction).ExecuteAffrows();

                            // 将更改标记为已提交
                            item.AcceptChanges();
                        }

                        transaction.Commit();
                        HandyControl.Controls.Growl.Info("提交完成！");
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        //记录日志，抛出异常（使用全局异常）或者返回自定义数据 
                        throw ex;
                    }
                }
            }

            OnRefreshButton();
        }

        /// <summary>
        /// 刷新列表
        /// </summary>
        private void OnRefreshButton()
        {
            List<ContentTemplateMapping> list = _fsql.Select<ContentTemplateMapping>().OrderBy(a => a.Id).ToList();
            DataList = new ObservableCollection<ContentTemplateMapping>(list);

        }

    }
}
